package com.wen.apiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.wen.apiclientsdk.model.User;


import java.util.HashMap;
import java.util.Map;

import static com.wen.apiclientsdk.utils.SignUtil.getSign;


/**
 * 调用第三方API 的 客户端
 */

public class ApiClient {

    private String accessKey;

    private String secretKey;

    private static final String GATEWAY_HOST = "http://127.0.0.1:8090";

    public ApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public  String getNameByGet(String name){
        HashMap<String,Object> paramMap = new HashMap<>();
        paramMap.put("name",name);
        String result = HttpUtil.get(GATEWAY_HOST+"/api/name/get",paramMap);
        System.out.println(result);
        return result;
    }

    public  String getNameByPost(String name){
        HashMap<String,Object> paramMap = new HashMap<>();
        paramMap.put("name",name);
        String result = HttpUtil.post(GATEWAY_HOST+"/api/name/post",paramMap);
        System.out.println(result);
        return result;
    }

    public  String getUserNameByPost(User user){
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post(GATEWAY_HOST+"/api/name/user")
                .addHeaders(getHeaderMap(json))
                .body(json).execute();
        System.out.println(httpResponse.getStatus());//输出状态码
        String result = httpResponse.body();
        System.out.println(result);
        return result;
    }

    private Map<String,String> getHeaderMap(String body){
        Map<String,String> headerMap = new HashMap<>();
        headerMap.put("accessKey",accessKey);

        //一定不能发送给后端，请求中不能出现明文
//        headerMap.put("secretKey",secretKey);
        headerMap.put("nonce", RandomUtil.randomNumbers(4));
        headerMap.put("body",body);
        headerMap.put("timestamp",String.valueOf(System.currentTimeMillis() / 1000));
        headerMap.put("sign",getSign(body,secretKey));
        return headerMap;
    }


}
